<template>
  <div class="public-model-index">
    <div class="search-content">
      <el-form :model="form" label-position="top" :inline="true">
        <el-form-item label="分类" v-if="mode !== 'rotationChart'">
          <el-select v-model="form.classify" placeholder="请选择">
            <el-option
              v-for="item in types"
              :key="item.type_id"
              :label="item.type_name"
              :value="item.type_id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input
            placeholder="请输入标题名称"
            suffix-icon="el-icon-search"
            v-model="form.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="form.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人">
          <person-search v-model="form.creator" />
        </el-form-item>
        <el-form-item class="buttons">
          <el-button size="small" @click="getTargetLists" type="primary"
            >查询</el-button
          >
          <el-button size="small" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div
      :class="[
        'table-content',
        mode !== 'allNews' && mode !== 'rotationChart' ? 'high-content' : '',
      ]"
    >
      <div class="buttons">
        <div class="left-buttons">
          <el-button
            icon="el-icon-circle-plus-outline"
            size="small"
            type="primary"
            @click="add"
            v-if="
              (mode === 'allNews' && ifCanAddNews) ||
              (mode === 'NoticesManage' && ifCanAddNotices) ||
              (mode === 'rotationChart' && ifCanAddRotation) ||
              (mode === 'RulesManage' && ifCanAddRules)
            "
            >新建</el-button
          >
          <el-button
            size="small"
            @click="openDialog"
            v-if="
              (mode === 'allNews' && ifCanChangeNews) ||
              (mode === 'NoticesManage' && ifCanChangeNotices) ||
              (mode === 'RulesManage' && ifCanChangeRules)
            "
            >维护分类</el-button
          >
        </div>
        <div
          class="right-buttons"
          v-if="
            ((mode === 'allNews' || mode === 'rotationChart') &&
              ifCanChangeNews) ||
            (mode === 'NoticesManage' && ifCanChangeNotices) ||
            (mode === 'RulesManage' && ifCanChangeRules)
          "
        >
          <el-button size="small" @click="operates('effective')"
            >批量生效</el-button
          >
          <el-button size="small" @click="operates('stop')">批量终止</el-button>
          <el-button size="small" @click="operates('delete')"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableData"
        ref="elTable"
        @cell-mouse-enter="cellMouseEnter"
        class="scroll-content"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          label="图片"
          v-if="mode === 'rotationChart'"
          width="78px"
        >
          <template slot-scope="scope">
            <el-popover placement="right" width="324" trigger="hover">
              <div class="img-box">
                <img
                  :src="scope.row.rotation_url"
                  width="300"
                  height="300"
                  alt=""
                />
              </div>
              <img
                :src="scope.row.rotation_url"
                width="28"
                height="28"
                alt=""
                slot="reference"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="标题">
          <template slot-scope="scope">
            <div class="scope-title">
              <span>{{ scope.row.title }}</span>
              <div
                v-if="scope.row.is_top && scope.row.status === 2"
                class="show-istop"
              >
                置顶
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="分类"
          width="100"
          prop="classify"
          show-overflow-tooltip
          v-if="mode !== 'rotationChart'"
        >
          <template slot-scope="scope">{{ scope.row.type.type_name }}</template>
        </el-table-column>
        <el-table-column label="发布范围" width="140" show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              scope.row.public_range === "all"
                ? "全员可见"
                : getPublicRange(scope.row.range)
            }}
          </template>
        </el-table-column>
        <el-table-column width="100" label="创建人">
          <template slot-scope="scope">
            <show-person :personInfo="scope.row.creator" />
          </template>
        </el-table-column>
        <el-table-column width="100" label="状态">
          <template slot-scope="scope">
            <div class="status-content">
              <div
                class="dot"
                :class="
                  scope.row.status !== 2
                    ? scope.row.status === 3
                      ? 'warning'
                      : 'fail'
                    : 'success'
                "
              ></div>
              <span>
                {{
                  scope.row.status === 0
                    ? "未发布"
                    : scope.row.status === 1
                    ? "已终止"
                    : scope.row.status === 2
                    ? "生效中"
                    : "待生效"
                }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="点击数"
          width="70"
          prop="click_num"
        ></el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column
          label="操作"
          width="50"
          v-if="
            ((mode === 'allNews' || mode === 'rotationChart') &&
              ifCanChangeNews) ||
            (mode === 'NoticesManage' && ifCanChangeNotices) ||
            (mode === 'RulesManage' && ifCanChangeRules)
          "
        >
          <template slot-scope="scope">
            <el-popover
              trigger="hover"
              width="100"
              popper-class="public-model-index-popover"
            >
              <div class="click-menu">
                <span
                  v-for="item in operateSelect.filter((item) =>
                    item.status.includes(scope.row.status) &&
                    item.mode === 'all'
                      ? true
                      : item.status.includes(scope.row.status) &&
                        item.mode.includes(mode)
                  )"
                  class="menu-item"
                  :key="item.value"
                  @click="menuClick[item.value]()"
                >
                  {{
                    item.value === "toTop"
                      ? scope.row.is_top
                        ? "取消置顶"
                        : "置顶"
                      : item.label
                  }}
                </span>
              </div>
              <i class="el-icon-more" slot="reference"></i>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationInfo.current_page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="paginationInfo.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationInfo.total"
        background
      >
      </el-pagination>
    </div>
    <el-dialog
      title="分类"
      :visible.sync="dialogVisible"
      width="30%"
      custom-class="public-model-index-dialog"
    >
      <div class="classify-list scroll-content">
        <div
          class="classify-item"
          v-for="item in classifyList"
          :key="item.type_id"
        >
          <el-input v-model="item.type_name" clearable></el-input>
          <i class="el-icon-delete" @click="deleteClassify(item.type_id)"></i>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          size="medium"
          @click="addClassify"
          >新建</el-button
        >
        <div class="buttons">
          <el-button @click="dialogVisible = false" size="small"
            >取 消</el-button
          >
          <el-button type="primary" @click="changeTypeSubmit" size="small"
            >确 定</el-button
          >
        </div>
      </span>
    </el-dialog>
    <el-drawer
      :title="drawerAbout.drawerTitle"
      :visible.sync="drawerAbout.drawer"
      :direction="drawerAbout.direction"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          :label="`已查看成员(${drawerAbout.lookedList.length})`"
          name="looked"
        >
          <show-person
            v-for="item in drawerAbout.lookedList"
            :personInfo="item"
            :key="item.empolyee_id"
          />
        </el-tab-pane>
        <el-tab-pane
          :label="`未查看成员(${drawerAbout.unlookList.length})`"
          name="unlook"
        >
          <show-person
            v-for="item in drawerAbout.unlookList"
            :personInfo="item"
            :key="item.empolyee_id"
          />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script>
import personSearch from "@/components/public/personSearch.vue";
import showPerson from "@/components/public/showPerson";
import router from "@/router";
import {
  changeIsTop,
  deleteInfoBlock,
  getTargetList,
  getTargetTypes,
  publishInfoBlock,
  stopInfoBlock,
  updateTypes,
  useRightNow,
} from "@/http/api";
import dayjs from "dayjs";
import ShowPerson from "@/components/public/showPerson.vue";
export default {
  name: "PublicModelIndex",
  components: { personSearch, showPerson, ShowPerson },
  props: ["mode"],
  data() {
    return {
      form: {
        classify: "",
        title: "",
        createTime: [],
        creator: {},
      },
      types: [
        { value: "1", label: "1" },
        { value: "2", label: "2" },
      ],
      tableData: [],
      paginationInfo: {
        current_page: 1,
        page_size: 10,
        total: 0,
      },
      operateSelect: [
        {
          label: "浏览记录",
          value: "record",
          status: [1, 2],
          mode: "all",
        },
        {
          label: "编辑",
          value: "edit",
          status: [0, 1, 2, 3],
          mode: "all",
        },
        {
          label: "终止",
          value: "stop",
          status: [2],
          mode: "all",
        },
        {
          label: "",
          value: "toTop",
          status: [2],
          mode: ["allNews", "RulesManage"],
        },
        {
          label: "删除",
          value: "delete",
          status: [0, 1, 2, 3],
          mode: "all",
        },
        {
          label: "发布",
          value: "publish",
          status: [0],
          mode: "all",
        },
        {
          label: "立即生效",
          value: "effect",
          status: [1, 3],
          mode: "all",
        },
      ],
      dialogVisible: false,
      classifyList: [],
      activeRowId: "",
      drawerAbout: {
        drawer: false,
        drawerTitle: "",
        direction: "rtl",
        lookedList: [],
        unlookList: [],
      },
      activeName: "looked",
      menuClick: {
        record: () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          );
          this.drawerAbout.drawerTitle = activeItem[0].title;
          this.drawerAbout.drawer = true;
          this.drawerAbout.lookedList = activeItem[0].viewed_employee;
          this.drawerAbout.unlookList = activeItem[0].un_viewed_employee;
        },
        edit: () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          )[0];
          let tab = this.$route.query.tab ?? this.$route.name;
          this.$router.push({
            name: "PublicModelAdd",
            query: {
              allInfo: JSON.stringify(activeItem),
              tab,
            },
          });
        },
        stop: async () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          )[0];
          let res = await stopInfoBlock([activeItem.id]);
          if (res.code === 20031) {
            this.$message.success("终止成功");
            this.getTargetLists();
          } else {
            this.$message.error(res.msg);
          }
        },
        toTop: async () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          )[0];
          let res = {};
          if (activeItem.is_top) {
            // 取消置顶
            res = await changeIsTop({
              is_top: 0,
              id: activeItem.id,
            });
          } else {
            // 置顶
            res = await changeIsTop({
              is_top: 1,
              id: activeItem.id,
            });
          }
          if (res.code === 20031) {
            this.$message.success("操作成功");
            this.getTargetLists();
          } else {
            this.$message.error(res.msg);
          }
        },
        delete: async () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          )[0];
          let res = await deleteInfoBlock(activeItem.id);
          if (res.code === 20021) {
            this.$message.success("删除成功");
            this.getTargetLists();
          } else {
            this.$message.error(res.msg);
          }
        },
        publish: async () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          )[0];
          let res = await publishInfoBlock(activeItem.id);
          if (res.code === 20031) {
            this.$message.success("发布成功");
            this.getTargetLists();
          } else {
            this.$message.error(res.msg);
          }
        },
        effect: async () => {
          let activeItem = this.tableData.filter(
            (item) => item.id === this.activeRowId
          )[0];
          let res = await useRightNow([activeItem.id]);
          if (res.code === 20031) {
            this.$message.success("操作成功");
            this.getTargetLists();
          } else {
            this.$message.error(res.msg);
          }
        },
      },
      ifCanChangeNews: false,
      ifCanAddNews: false,
      ifCanAddRotation: false,
      ifCanAddNotices: false,
      ifCanChangeNotices: false,
      ifCanAddRules: false,
      ifCanChangeRules: false,
    };
  },
  mounted() {
    this.getTargetClasses();
    this.getTargetLists();
    let authDetail = JSON.parse(localStorage.getItem("authority"));
    if (authDetail === "all") {
      this.ifCanChangeNews = true;
      this.ifCanAddNews = true;
      this.ifCanAddRotation = true;
      this.ifCanAddNotices = true;
      this.ifCanChangeNotices = true;
      this.ifCanAddRules = true;
      this.ifCanChangeRules = true;
    } else {
      this.ifCanChangeNews = authDetail.includes("NewsManageChange")
        ? true
        : false;
      this.ifCanAddNews = authDetail.includes("AddNews") ? true : false;
      this.ifCanAddRotation = authDetail.includes("AddRotation") ? true : false;
      this.ifCanAddNotices = authDetail.includes("AddNotices") ? true : false;
      this.ifCanChangeNotices = authDetail.includes("NoticesManageChange")
        ? true
        : false;
      this.ifCanAddRules = authDetail.includes("AddRules") ? true : false;
      this.ifCanChangeRules = authDetail.includes("RulesManageChange")
        ? true
        : false;
    }
  },
  methods: {
    handleSizeChange(page_size) {
      this.paginationInfo.page_size = page_size;
      this.getTargetLists();
    },
    handleCurrentChange(current_page) {
      this.paginationInfo.current_page = current_page;
      this.getTargetLists();
    },
    add() {
      router.push({
        name: "PublicModelAdd",
        query: {
          tab: this.mode,
        },
      });
    },
    openDialog() {
      this.getTargetClasses();
      this.dialogVisible = true;
    },
    addClassify() {
      this.classifyList.push({
        type_id: Math.floor(Math.random() * 1000),
        belong_block_id: this.mode === "allNews" ? "NewsManage" : this.mode,
        type_name: "",
      });
    },
    deleteClassify(type_id) {
      this.classifyList = this.classifyList.filter(
        (item) => item.type_id !== type_id
      );
    },
    async operates(operatesMode) {
      if (!this.$refs.elTable.selection.length) {
        this.$message({
          message: "请至少选择一条新闻",
          type: "warning",
        });
      }
      if (operatesMode === "stop") {
        let res = await stopInfoBlock(
          this.$refs.elTable.selection.map((item) => item.id)
        );
        if (res.code === 20031) {
          this.$message.success("终止成功");
          this.getTargetLists();
        } else {
          this.$message.error(res.msg);
        }
      }
      if (operatesMode === "delete") {
        this.$alert(`确认删除${this.$refs.elTable.selection.length}条信息？`, {
          confirmButtonText: "确定",
          showCancelButton: true,
          type: "warning",
          callback: (action) => {
            if (action === "confirm") {
              let ifFail = false;
              this.$refs.elTable.selection.forEach(async (item) => {
                let res = await deleteInfoBlock(item.id);
                if (res.code !== 20021) {
                  ifFail = true;
                }
              });
              if (ifFail) {
                this.$message.error("删除失败");
              } else {
                this.$message.success("删除成功");
              }
              this.getTargetLists();
            }
          },
        });
      }
      if (operatesMode === "effective") {
        let res = await useRightNow(
          this.$refs.elTable.selection.map((item) => item.id)
        );
        if (res.code === 20031) {
          this.$message.success("操作成功");
          this.getTargetLists();
        } else {
          this.$message.error(res.msg);
        }
      }
    },
    cellMouseEnter(row) {
      this.activeRowId = row.id;
    },
    handleClick(item) {
      console.log("%c Line:444 🍑🍑🍑 item", "color:#ed9ec7", item);
    },
    async getTargetClasses() {
      let res = {};
      if (this.mode === "allNews") {
        res = await getTargetTypes("NewsManage");
      } else {
        res = await getTargetTypes(this.mode);
      }
      if (res.code === 20041) {
        this.types = res.data;
        this.classifyList = res.data.filter((item) => {
          return item.type_name !== "其他";
        });
      }
    },
    async changeTypeSubmit() {
      let res = await updateTypes({
        InfoBlockType: this.classifyList,
        belong_block_id:
          this.mode === "allNews"
            ? "NewsManage"
            : this.mode === "NoticesManage"
            ? "NoticesManage"
            : undefined,
      });
      this.getTargetClasses();
      this.dialogVisible = false;
    },
    reset() {
      this.form = {
        classify: "",
        title: "",
        createTime: [],
        creator: {},
      };
    },
    async getTargetLists() {
      let res = await getTargetList(this.mode, {
        ...this.form,
        ...this.paginationInfo,
        mode: 'all'
      });
      if (res.code === 20041) {
        this.tableData = res.data.rows;
        this.paginationInfo.total = res.data.page.total;
        this.tableData.forEach((element) => {
          element.create_time = dayjs(element.create_time).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
      }
    },
    getPublicRange(range) {
      let res = "";
      res += range.dept.map((item) => item.dept_name).join("、");
      if (range.employee.length && range.employee[0] !== null) {
        if (res) res += " & ";
        res += range.employee.map((item) => item.employee_name).join(" & ");
      }
      return res;
    },
  },
};
</script>

<style lang="less" scoped>
.public-model-index {
  .search-content .el-form {
    display: flex;
    .el-form-item {
      margin-bottom: 0;
      &.buttons {
        width: 200px;
        margin-left: 10px;
        display: flex;
        align-items: center;
        margin-top: 20px;
      }
    }
  }
  .table-content {
    margin-top: 20px;
    height: calc(100vh - 320px);
    .buttons {
      display: flex;
      justify-content: space-between;
      & > div {
        display: flex;
      }
    }
    .el-table {
      height: calc(100vh - 420px);
      margin: 8px 0 4px;
      &::before {
        display: none;
      }
      .status-content {
        display: flex;
        align-items: center;
        .dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #3c8cff;
          margin-right: 4px;
          &.fail {
            background-color: #ff5046;
          }
          &.warning {
            background: #ff9801;
          }
        }
      }
      .scope-title {
        display: flex;
        .show-istop {
          margin-left: 4px;
          font-size: 12px;
          border-radius: 4px;
          padding: 0 4px;
          color: #fff;
          background: linear-gradient(228deg, #ffc902, #ff9801);
        }
      }
    }
    &.high-content {
      height: calc(100vh - 270px);
      .el-table {
        height: calc(100vh - 370px);
      }
    }
    .el-pagination {
      display: flex;
      justify-content: end;
    }
  }
  /deep/ .el-drawer {
    .el-drawer__header {
      border-bottom: 1px solid #e8eaed;
      padding-bottom: 20px;
      margin-bottom: 10px;
    }
    .el-drawer__body {
      padding: 0 10px;
      .show-person {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
<style lang="less">
.public-model-index-popover {
  min-width: 100px;
  padding: 12px 0;
  .click-menu {
    display: flex;
    flex-direction: column;
    padding: 0;
    .menu-item {
      font-size: 16px;
      line-height: 30px;
      padding: 0 10px;
      height: 30px;
      cursor: pointer;
      &:hover {
        background-color: #ecf5ff;
        color: #71b6ff;
      }
    }
  }
}
.public-model-index-dialog {
  .classify-list {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 300px);
    .classify-item {
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      i {
        margin: 0 10px;
        font-size: 20px;
        cursor: pointer;
      }
    }
  }
  .el-dialog__footer {
    border-top: 1px solid #d9d9d9;
    .dialog-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
